package server

import (
	"fmt"
	"net"
	"server5/Interface"
	"server5/protobuf"
	"server5/utils"
	"time"
)

type Server struct {
	Ip   string
	Port int
}

func NewServer() *Server {
	return &Server{
		Ip:   utils.GlobalObject.IpAddress,
		Port: utils.GlobalObject.Port,
	}
}

func (s *Server) Start() {

	//开启消息队列
	GetMsgManager().StartWorkerPool()

	//初始化Listen
	listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", s.Ip, s.Port))
	if err != nil {
		fmt.Printf("%+v", err)
		return
	}
	defer listener.Close()

	//Debug
	fmt.Println("服务器启动成功，正在监听",s.Port)

	var connId uint32 = 0
	//一直监听新连接
	for {
		conn, err := listener.Accept()
		if err != nil {
			fmt.Printf("%+v", err)
			continue
		}
		conn.SetDeadline(time.Now().Add(time.Duration(1200)*time.Second))//设置120s短连接
		//有新连接就开一个协程处理
		connId++
		go NewConnection(conn, connId).Start()
	}

}

func (s *Server) Stop() {
	GetConnManager().Clear()
}

func (s *Server) AddRouter(msgType protobuf.MsgType, router Interface.IRouter) {
	GetMsgManager().AddRouter(msgType, router)
}
